package com.laiat.logclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.laiat.logservice.ILogService;
import com.laiat.logservice.Message;

public class LogActivity extends Activity implements OnClickListener {
	
	private static final String TAG = LogActivity.class.getSimpleName();

	private ILogService logService;
	private LogConnection conn;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Request bind to the service
        conn = new LogConnection();
        Intent intent = new Intent("com.laiat.logservice.ILogService");
        intent.putExtra("version", "1.0");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        
        // attach listener to button
        ((Button)findViewById(R.id.button1)).setOnClickListener(this);
    }

	@Override
	public void onClick(View arg0) {
		try {
			logService.log_d("LogClient", "Hello from onClick()");
			
			Message msg = new Message(Parcel.obtain());
			msg.setTag("LogClient");
			msg.setText("Hello from onClick() version 1.1");
			logService.log(msg);
		} catch(RemoteException e) {
			Log.e(TAG, "onClick failed", e);
		}
		
	}
	
	@Override
	protected void onDestroy() {
		Log.d(TAG, "onDestroy");
		
		unbindService(conn);
		
		super.onDestroy();
	}



	private class LogConnection implements ServiceConnection {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			logService = ILogService.Stub.asInterface(service);
			Log.i(TAG, String.format("connected to '%s'", name));
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			logService = null;
			Log.i(TAG, String.format("disconnected from '%s'", name));
		}
	}
    
}